# -*- coding: utf-8 -*-
from SimpleXMLRPCServer import SimpleXMLRPCServer
from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler

import os, commands, urllib, base64, shutil, sys, time, subprocess, signal

def runCmd(cmd, timeout=None):
	procKilled = 0
        ph_out = None # process output
        ph_err = None # stderr
        ph_ret = None # return code

        p = subprocess.Popen(cmd, shell=True,
                     stdout=subprocess.PIPE,
                     stderr=subprocess.PIPE)
# if timeout is not set wait for process to complete
        if not timeout:
                ph_ret = p.wait()
        else:
                fin_time = time.time() + timeout
                while p.poll() == None and fin_time > time.time():
                        time.sleep(1)

    # if timeout reached, raise an exception
        if fin_time < time.time():
        # starting 2.6 subprocess has a kill() method which is preferable
        # p.kill()
                try:
                        os.kill(p.pid, signal.SIGKILL)
			procKilled = 1
                except:
                        print "process does not exist"

        ph_ret = p.returncode

	if procKilled == 0:
	        ph_out, ph_err = p.communicate()
	else:
		ph_out = "Output too long, not acceptable"
		ph_err = "Output too long, not acceptable"

        return (ph_out, ph_err, ph_ret)

def executeCode_RPCServer(fileName, language):
	output = None
	if language == "_NO_LANG":
		return "_NO_LANG_SENT"

	try:
		output = commands.getoutput("dos2unix " + fileName)
	except:
		return "_DOS2UNIX_ERROR"


        try:
		cmd = "su -c '" + language + " " + fileName + "' www-data"
		(ph_out, ph_err, ph_ret) = runCmd(cmd, timeout = 1)
		if len(ph_out) > 100:
        		ph_out = ph_out[0:100]

        except:
                return "_CMD_ERROR"

	if ph_out != "":
		return ph_out
	else:
		return ph_err


class RequestHandler(SimpleXMLRPCRequestHandler):
	        rpc_paths = ('/RPC2',)

#
# Just a small argument handler here, will enhance later
#
serverIP = sys.argv[1]
port = int(sys.argv[2])

server = SimpleXMLRPCServer((serverIP, port), requestHandler=RequestHandler)
server.register_introspection_functions()

server.register_function(executeCode_RPCServer, 'execCode')

server.serve_forever()
